package org.restql.db.operation;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.restql.db.resource.DatabaseResource;
import org.restql.db.resource.RequestResource;
import org.restql.webapp.RestQLException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public abstract class DatabasePutPost extends DatabaseOperation {

	private static Log logger = LogFactory.getLog(DatabasePutPost.class);

	protected DatabasePutPost(DatabaseResource databaseResource, RequestResource requestResource) {
		super(databaseResource, requestResource);
	}

	public void executeSql(ServletInputStream inputStream) throws RestQLException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();
			Document postedXml = builder.parse(inputStream);
			Node root = postedXml.getFirstChild();
			if (! root.getNodeName().equals(this.requestResource.getDbName())) {
				logger.error("Root of supplied XML does not match resource.");
				throw new RestQLException("Improper root node: " + root.getNodeName(), null);
			}
			NodeList tables = root.getChildNodes();
			for (int i = 0; i < tables.getLength(); i++) {
				if (tables.item(i).getNodeType() == Node.ELEMENT_NODE) {
					Node insertNode = tables.item(i);
					doOperation(insertNode);
				}
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			throw new RestQLException("Error parsing XML in PUT", e);
		} catch (SAXException e) {
			e.printStackTrace();
			throw new RestQLException("Error parsing XML in PUT", e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RestQLException("Error reading request", e);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RestQLException("Error executing SQL exception... fields correct?", e);
		}
	}

	protected abstract void doOperation(Node n) throws SQLException;

}
